package com.shi.util;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.shi.properties.SysProperties;

/**
 * 密码加密、校验工具
 */
public class PasswordUtil {

    /**
     * 对密码加密
     *
     * @param rawPassword
     * @return
     */
    public static String encode(String rawPassword) {
        if (rawPassword == null || rawPassword.length() == 0) {
            throw new RuntimeException("原始密码不能为空");
        }
        SysProperties properties = SpringUtil.getBean(SysProperties.class);
        HMac hmac = SecureUtil.hmac(HmacAlgorithm.HmacSHA256, properties.getEncodeKey());
        return hmac.digestHex(rawPassword);
    }

    /**
     * 原始密码和加密密码进行比较
     *
     * @param encodePassword
     * @param rawPassword
     * @return
     */
    public static Boolean match(String encodePassword, String rawPassword) {
        if (encodePassword == null || rawPassword == null || encodePassword.length() == 0 || rawPassword.length() == 0) {
            return false;
        }
        String encoded = encode(rawPassword);
        return encodePassword.equals(encoded);
    }
}
